package com.wjh.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wjh.api.service.MemberService;
import com.wjh.base.BaseController;
import com.wjh.bean.Constants;
import com.wjh.bean.Result;
import com.wjh.dao.UserDao;
import com.wjh.mq.RegisterMailboxProducer;
import com.wjh.pojo.UserEntity;
import com.wjh.utils.MD5Util;
import com.wjh.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @Author: 王金海
 * @Description:
 * @Date: Created by Administrator on 2018/6/7.
 * @Modified By:
 */
@RestController
@Slf4j
public class MemberServiceImpl extends BaseController implements MemberService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RegisterMailboxProducer registerMailboxProducer;


    @Value("${messages.queue}")
    private String MESSAGESQUEUE;
//    @Override
//    public Result testRest() {
//        return success(Arrays.asList(1,2,3,4));
//    }
//
//    @Override
//    public Result testSetRedis(String key, String value) {
//        baseRedisService.setString(key,value,null);
//        return success();
//    }
//
//    @Override
//    public Result testGetRedis(String key) {
//        Object obj = baseRedisService.getString(key);
//        if (ObjectUtils.isEmpty(obj)) {
//            return error(300,"Redis中没获取到Key为"+key+"的值");
//        }
//        return success(obj);
//    }
//
//    @Override
//    public Result testDelRedis(String key) {
//        baseRedisService.delKey(key);
//        return success();
//    }

    @Override
    public Result findUserById(Integer id) {
        UserEntity userEntity = userDao.findByID(id);
        if (ObjectUtils.isEmpty(userEntity)) {
            return error("未找到用户信息");
        }
        return success(userEntity);
    }

    @Override
    public Result findUserByOpenId(@RequestParam("openId") String openId) {
        UserEntity userEntity = userDao.findUserByOpenId(openId);
        if (ObjectUtils.isEmpty(userEntity)) {
            return error(Constants.HTTP_RES_CODE_201,"用户未绑定");
        }
        return getLoginToken(userEntity);
    }

    @Override
    public Result regust(@RequestBody UserEntity userEntity) {
        String password = userEntity.getPassword();
        if (StringUtils.isEmpty(password)) {
            return error("密码不能为空");
        }
        userEntity.setPassword(MD5Util.MD5(password));
        userEntity.setCreated(new Date());
        userEntity.setUpdated(new Date());
        int integer = userDao.insertUser(userEntity);
        if (integer<=0) {
            return error("注册失败");
        }
        //异步发送邮件
        String message = message(userEntity.getEmail());
        sendMsg(message);
        return success("注册成功");
    }

    @Override
    public Result login(@RequestBody UserEntity userEntity) {
        String username = userEntity.getUsername();
        String password = userEntity.getPassword();
        if (StringUtils.isEmpty(username)) {
            return error("用户名不能为空");
        }
        if (StringUtils.isEmpty(password)) {
            return error("密码不能为空");
        }
        UserEntity user = userDao.findByUsername(username);
        if (ObjectUtils.isEmpty(user)) {
            return error("用户不存在");
        }
        if (!user.getPassword().equals(MD5Util.MD5(password))) {
            return error("密码错误");
        }
        return getLoginToken(user);
    }

    @Override
    public Result qqrelation(@RequestBody UserEntity userEntity) {
        String openid = userEntity.getOpenid();
        //1、验证参数
        if (StringUtils.isEmpty(openid)) {
            return error("openid不能为空");
        }
        //2、用户名密码登陆
        Result result = login(userEntity);
        if (result.getCode()!= Constants.HTTP_RES_CODE_200) {
            return result;
        }
        //3、获取token
        JSONObject jsonObject =(JSONObject) result.getData();
        String token = (String)jsonObject.get("token");
        //4、根据token获取用户信息
        Result resultuser = findUser(token);
        if (resultuser.getCode()!= Constants.HTTP_RES_CODE_200) {
            return resultuser;
        }
        UserEntity entity = (UserEntity)resultuser.getData();
        //5、更新openid
        int integer = userDao.updataUserOpenid(openid,entity.getId());
        if (integer<=0) {
            return error("绑定失败");
        }
        //6、返回token
        return getLoginToken(entity);
    }

    /**
     * 根据用户信息获取token
     * @param user
     * @return
     */
    private Result getLoginToken(UserEntity user){
        String token = TokenUtils.getToken();
        int count = userDao.updataUserToken(token, user.getId());
        if (count<=0) {
            return error("token更新失败");
        }
        baseRedisService.setString(token,user.getId()+"",Constants.MEMBER_TOKEN_TIME);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token", token);
        return success(jsonObject);
    }

    @Override
    public Result findUser(@RequestParam("token") String token) {
        String userId = (String)baseRedisService.getString(token);
        if (ObjectUtils.isEmpty(userId)) {
            return error("token错误或已过期");
        }
        UserEntity userEntity = userDao.findByID(Integer.parseInt(userId));
        if (ObjectUtils.isEmpty(userEntity)) {
            return error("用户不存在");
        }
        String dbToken = userEntity.getToken();
        if (!token.equals(dbToken)) {
            return error("账号已在其他地方登陆");
        }
        userEntity.setPassword(null);
        return success(userEntity);
    }


    private String message(String mail) {
        JSONObject root = new JSONObject();
        JSONObject header = new JSONObject();
        header.put("interfaceType", Constants.SMS_MAIL);
        JSONObject content = new JSONObject();
        content.put("mail", mail);
        root.put("header", header);
        root.put("content", content);
        return root.toJSONString();
    }

    private void sendMsg(String json) {
        ActiveMQQueue activeMQQueue = new ActiveMQQueue(MESSAGESQUEUE);
        registerMailboxProducer.sendMsg(activeMQQueue, json);
    }

}


